
package de.lmu.mvs.lerngruppenfinder;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonValue;

import de.lmu.mvs.lerngruppenfinder.interests.InterestNode;
import de.lmu.mvs.lerngruppenfinder.interests.InterestTree;
import de.lmu.mvs.lerngruppenfinder.utils.ApplicationController;
import de.lmu.mvs.lerngruppenfinder.utils.Constants;
import de.lmu.mvs.lerngruppenfinder.utils.DateDistanceComparator;
import de.lmu.mvs.lerngruppenfinder.utils.FileApi;
import de.lmu.mvs.lerngruppenfinder.utils.ServerConnector;
import de.lmu.mvs.lerngruppenfinder.utils.ServerConnector.ServerConnectorListener;
import de.lmu.mvs.lerngruppenfinder.utils.ServerConnector.ServerError;
import de.lmu.mvs.lerngruppenfinder.utils.Utils;
import android.R.id;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Contacts.Groups;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class DashboardActivity extends Activity implements OnItemClickListener {

	private static final String TAG = DashboardActivity.class.getSimpleName();

	HashMap<Integer, Group> allGroupsMap = new HashMap<Integer, DashboardActivity.Group>();
	
	InterestTree mInterestTree = null;

	JsonArray interessen;
	HashMap<String, String> row = new HashMap<String, String>();
	// Speichert den RequestCode um die Anfrage f�r AddGroup zu identifizieren.
	public static final int ADDGROUPREQUEST = 100;
	//private ArrayList<String> liste = new ArrayList<String>();
	ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

	//private SimpleAdapter adapter = null;
	private GroupAdapter groupAdapter = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dashboard);


		LocationManager locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
		Location location = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
		getGroupsRadius(48.15, 11.57, 1000.0);

		if(location != null) {
			// SubscribedGroups
			// GroupsInRadius
		}

		LocationListener locationListener = new LocationListener() {

			@Override
			public void onLocationChanged(Location location) {

				getGroupsRadius(48.15, 11.57, 1000.0);
			}

			@Override
			public void onStatusChanged(String provider, int status,
					Bundle extras) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProviderEnabled(String provider) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProviderDisabled(String provider) {
				// TODO Auto-generated method stub

			}
		};

		locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

		// Listview holen
		final ListView listview = (ListView) findViewById(R.id.listView1);

		row.put("Name", "Name");
		row.put("Fachgebiet", "Fachgebiet");
		row.put("Termin", "Termin");

		groupAdapter = new GroupAdapter(this, new ArrayList<DashboardActivity.Group>());

		listview.setOnItemClickListener(this);

		ServerConnector.getInterests(new ServerConnectorListener<JsonArray>() {

			@Override
			public void requestFinished(JsonArray json) {
				interessen = json;
			}

			@Override
			public void requestError(ServerError error) {
				// TODO Auto-generated method stub

			}} );

		fillList();
		
		setupInterests();

		groupAdapter.notifyDataSetChanged();
	}


	public void updateAdapter() {

		List<Group> groups = new ArrayList<DashboardActivity.Group>();

		for (Map.Entry<Integer, Group> entity : allGroupsMap.entrySet()) {
			groups.add(entity.getValue());
		}
		
		Collections.sort(groups, new DateDistanceComparator());
		
		groupAdapter = new GroupAdapter(this, groups);
	}


	private void getGroupsRadius (double latitude, double longitude, double distance) {

		ServerConnector.getGroupsInRadius(new ServerConnectorListener<JsonArray>() {

			@Override
			public void requestFinished(JsonArray json) {

				JsonValue groupsRadius;

				Log.i(TAG, "Try loading list from server...");
				if((groupsRadius = FileApi.readJsonFromStorage("groups", DashboardActivity.this)) != null){
					if(groupsRadius.isArray()) {	


						for (JsonValue value : json) {
							Log.i(TAG, "Enter for (JsonValue value : json)");

							String id = value.asObject().get("id").toString().replaceAll("^\"|\"$", "");
							Log.i(TAG, "GET ID");
							String gpsX = value.asObject().get("gpsX").toString().replaceAll("^\"|\"$", "");
							Log.i(TAG, "GET gpsX");
							String gpsY = value.asObject().get("gpsY").toString().replaceAll("^\"|\"$", "");
							Log.i(TAG, "GET gpsY");
							String name = value.asObject().get("name").toString().replaceAll("^\"|\"$", "");
							Log.i(TAG, "GET name");
							String fachgebiet = value.asObject().get("fachgebiet").toString().replaceAll("^\"|\"$", "");
							Log.i(TAG, "GET fachgebiet");
							String gebaeude = value.asObject().get("gebaeude").toString().replaceAll("^\"|\"$", "");
							Log.i(TAG, "GET gebaeude");
							String datum = value.asObject().get("datum").toString().replaceAll("^\"|\"$", "");
							Log.i(TAG, "GET datum");
							String ablauf = value.asObject().get("ablauf").toString().replaceAll("^\"|\"$", "");
							Log.i(TAG, "GET ablauf");

							int groupId = Integer.parseInt(id);
							Group group;

							if(allGroupsMap.containsKey(groupId)) {
								group = allGroupsMap.get(groupId);
							}
							else {
								group = new Group();
							}
							group.setItems(id, gpsX, gpsY, name, fachgebiet, gebaeude, datum, ablauf);

							allGroupsMap.put(groupId, group);

						}
						updateAdapter();
						((ListView)findViewById(R.id.listView1)).setAdapter(groupAdapter);

					}
				}
			}

			@Override
			public void requestError(ServerError error) {
				// TODO Auto-generated method stub

			}
		}, latitude, longitude, distance);
	}


	private void fillList () {



		ServerConnector.getSubscribedGroups(new ServerConnectorListener<JsonArray>() {

			@Override
			public void requestFinished(JsonArray json) {
				// TODO Auto-generated method stub


				JsonValue interestJson;
				Log.i(TAG, "Try loading list from server...");
				if((interestJson = FileApi.readJsonFromStorage("interests", DashboardActivity.this)) != null){
					if(interestJson.isArray()){

						for (JsonValue value : json) {

							String id = "";

							/*
							DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
							DateTime dt = formatter.parseDateTime(string);
							 */

							Log.i(TAG, "Enter for (JsonValue value : json)");

							id = value.asObject().get("id").toString().replaceAll("^\"|\"$", "");

							int UID = Integer.parseInt(id);
							Group group;
							if(allGroupsMap.containsKey(UID)) {
								group = allGroupsMap.get(UID);
								group.subscribed = true;
							}
							else {
								group = new Group();
								group.subscribed = true;
							}

							allGroupsMap.put(UID, group);
							groupAdapter.notifyDataSetChanged();

						}		
					}
				} else {
					// get list from server
					Log.i(TAG, "No files in storage available, try loading interests from server...");
					ServerConnector.getInterests(new ServerConnectorListener<JsonArray>() {

						@Override
						public void requestFinished(JsonArray json) {

							for (JsonValue value : json) {

								String id = "";


								/*
								DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
								DateTime dt = formatter.parseDateTime(string);
								 */

								id = value.asObject().get("id").toString().replaceAll("^\"|\"$", "");

								Group group = new Group();
								group.id = id;
								//								group.setItems(id, gpsX, gpsY, name, fachgebiet, gebaeude, datum, ablauf);
								//								subscribedGroupsList.add(group);

								allGroupsMap.put(null, group);

								groupAdapter.notifyDataSetChanged();


							}		
						}
						@Override
						public void requestError(ServerError error) {
							Log.e(TAG, error.getErrorMessage());
							Toast.makeText(getBaseContext(), "Error loading filters", Toast.LENGTH_LONG).show();
						}

					});	
				}	
			}	
			@Override
			public void requestError(ServerError error) {
				// TODO Auto-generated method stub

			}
		}, FileApi.readLoginCredentials().id);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_logout:
	        	FileApi.deleteLoginCredentials();
	        	startActivity(new Intent(this, MainActivity.class));
	        	finish();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public void startAddGroupActivity(View view) {
		startActivityForResult(new Intent(this, AddGroupActivity.class),
				ADDGROUPREQUEST);
	}

	public void startUserProfileActivity(View view) {
		startActivity(new Intent(this, UserProfileActivity.class));
	}

	public void startGroupsMapActivity(View view){
		startActivity(new Intent(this, GroupsMapActivity.class));
	}


	@Override
	public void onItemClick(AdapterView<?> groupAdapter, View view, int position, long id) {
		// TODO Auto-generated method stub


		//Log.i(TAG, "onItemClick(AdapterView<?>");

		Group g = (Group) groupAdapter.getItemAtPosition(position);
		String item = g.id;
		//Toast.makeText(DashboardActivity.this, "You clicked on: " + item + " ID: " + id, Toast.LENGTH_LONG).show();

		int UserID = Integer.parseInt(item);

		Intent i = new Intent (this, GroupDetailActivity.class);
		i.putExtra("id", UserID);
		startActivity(i);

	}


	private class GroupAdapter extends BaseAdapter {

		private List<Group> groupList = new ArrayList();
		private Context mContext;

		public GroupAdapter (Context context, List<Group> groupList) {
			super();
			mContext = context;
			this.groupList = groupList;
		}

		@Override
		public int getCount() {
			return groupList.size();
		}

		@Override
		public Object getItem(int position) {
			return groupList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {


			Log.i(TAG, "getView Methode");
			Group g = (Group) getItem(position);
			LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
			convertView = inflater.inflate(R.layout.daashboardrow, parent, false);
			
			DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
			DateTime time = format.parseDateTime(g.datum);
			
			String timeString = Utils.formatTime(time.getMillis());

			((TextView) convertView.findViewById(R.id.DASHBOARD_ROW_DATE)).setText(timeString);
			if(mInterestTree != null){
				InterestNode node = mInterestTree.find(Integer.parseInt(g.fachgebiet));
				if(node != null){
					((TextView) convertView.findViewById(R.id.DASHBOARD_INTERESTS)).setText(node.getInterestName());
				}
			}
			((TextView) convertView.findViewById(R.id.DASHBOARD_ROW_NAME)).setText(g.name);

			((TextView)convertView.findViewById(R.id.DASHBOARD_IMAGE_SUBSCRIBED)).setTypeface(ApplicationController.getTypeFace());
			
			if(g.subscribed){
				convertView.findViewById(R.id.DASHBOARD_IMAGE_SUBSCRIBED).setVisibility(View.VISIBLE);
			} else {
				convertView.findViewById(R.id.DASHBOARD_IMAGE_SUBSCRIBED).setVisibility(View.GONE);
			}

			return convertView;
		}

	}

	public class Group {

		public String id;
		public String gpsX;
		public String gpsY;
		public String name;
		public String fachgebiet;
		public String gebaeude;
		public String datum;
		public String ablauf;
		public boolean subscribed; 

		Group() {

			id = "";
			gpsX = "";
			gpsY = "";
			name = "";
			fachgebiet = "";
			gebaeude = "";
			datum = "";
			ablauf = "";
			subscribed = false;
		}

		public void setItems(String id, String gpsX, 
				String gpsY, String name, 
				String fachgebiet, String gebaeude, 
				String datum, String ablauf) {

			this.id = id;
			this.gpsX = gpsX;
			this.gpsY = gpsY;
			this.name = name;
			this.fachgebiet = fachgebiet;
			this.gebaeude = gebaeude;
			this.datum = datum;
			this.ablauf = ablauf;

		}



	}

	
	/**
	 * Get interests from storage or server and initiate views
	 */
	private void setupInterests(){
		// load interest tree
		JsonValue interestJson;
		Log.i(TAG, "Try loading interests from storage...");
		if((interestJson = FileApi.readJsonFromStorage("interests", this)) != null){
			if(interestJson.isArray()){
				mInterestTree = new InterestTree(interestJson.asArray());
			}
		} else {
			// get list from server
			Log.i(TAG, "No files in storage available, try loading interests from server...");
			ServerConnector.getInterests(new ServerConnectorListener<JsonArray>() {

				@Override
				public void requestFinished(JsonArray json) {
					mInterestTree = new InterestTree(json);
				}
				@Override
				public void requestError(ServerError error) {
					Log.e(TAG, error.getErrorMessage());
					Toast.makeText(getBaseContext(), "Error loading filters", Toast.LENGTH_LONG).show();
				}
			});
		}
	}
}

